#include <iostream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>
#include <functional>
#include "Task.hpp"
#include"Channel.hpp"
using namespace std;

using work_t = function<void()>;
enum
{
    OK = 0,
    ARGCEROOR,
    PIPEROOR,
    FORKEROOR,
};

class ProcessPool
{
public:
    ProcessPool(int n,work_t w):nums(n),work(w)
    {}
// work_t work:回调
int InitProcesspool()
{

    for (int i = 0; i < nums; i++)
    {
        // 1 创建管道
        int pipedor[2] = {0};
        int n = pipe(pipedor);
        if (n < 0)
        {
            return PIPEROOR;
        }
        // 2 创建指定个数的进程
        pid_t pid = fork();
        if (pid < 0)
        {
            return FORKEROOR;
        }
        if (pid == 0)
        {
            // child 进程
            close(pipedor[1]);
            dup2(pipedor[0], 0);
            work();

            // 退出
            exit(0);
        }
        // 父进程
        close(pipedor[0]);
        channels.emplace_back(pipedor[1], pid);
        // channel c(pipedor[1],pid);
        // channels.push_back(c);
        // pid_t id = waitpid(pid, nullptr, 0);
    }
    return OK;
}
void DispatchTask()
{
    int who = 0;
    int n = 10;
    while (n--)
    {
        // 选择一个任务(int)
        int retask = tm.SelectTask();
        // 选择一个子进程
        channel &cee = channels[who++];
        who %= channels.size();

        cout << "*****************************************" << endl;
        cout << "send  " << retask << "channl: " << cee.Name() << "---" << n << endl;
        cout << "*****************************************" << endl;

        // 派发任务
        cee.Send(retask);
        sleep(1);
    }
}
void CloseProcessPool()
{
    for (auto &c : channels)
    {
        c.Close();
    }
    for (auto &c : channels)
    {
        pid_t rid = waitpid(c.Id(), nullptr, 0);
        if (rid > 0)
        {
            cout << "     child   " << rid << "   wait   " << endl;
        }
    }
}


private:
    vector<channel> channels;
    int nums;
    work_t work;
};





